package com.example.provider.controller;

import com.example.provider.model.User;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final Map<Long, User> users = new ConcurrentHashMap<>();
    private final AtomicLong counter = new AtomicLong();

    @Value("${server.port}")
    private String serverPort;

    @PostConstruct
    public void init() {
        // Initialize with some default users
        long id1 = counter.incrementAndGet();
        users.put(id1, new User(id1, "Alice from port " + serverPort, serverPort));

        long id2 = counter.incrementAndGet();
        users.put(id2, new User(id2, "Bob from port " + serverPort, serverPort));
    }

    @GetMapping
    public ResponseEntity<Map<Long, User>> getAllUsers() {
        System.out.println("GET /api/users called on port: " + serverPort);
        return ResponseEntity.ok(users);
    }

    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User newUser) {
        System.out.println("POST /api/users called on port: " + serverPort);
        long id = counter.incrementAndGet();
        newUser.setId(id);
        newUser.setPort(serverPort);
        users.put(id, newUser);
        return ResponseEntity.ok(newUser);
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User updatedUser) {
        System.out.println("PUT /api/users/" + id + " called on port: " + serverPort);
        if (users.containsKey(id)) {
            updatedUser.setId(id);
            updatedUser.setPort(serverPort);
            users.put(id, updatedUser);
            return ResponseEntity.ok(updatedUser);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
        System.out.println("DELETE /api/users/" + id + " called on port: " + serverPort);
        if (users.containsKey(id)) {
            users.remove(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
        System.out.println("GET /api/users/" + id + " called on port: " + serverPort);
        User user = users.get(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
} 